package org.jeecg.modules.exZbidOpeningArrange.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exBiddingRoom.entity.ExBiddingRoom;
import org.jeecg.modules.exBiddingRoom.service.IExBiddingRoomService;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.service.IExSectionService;
import org.jeecg.modules.exZbidOpeningArrange.entity.ExZbidChangdiandbd;
import org.jeecg.modules.exZbidOpeningArrange.entity.ExZbidOpeningArrange;
import org.jeecg.modules.exZbidOpeningArrange.service.IExZbidChangdiandbdService;
import org.jeecg.modules.exZbidOpeningArrange.service.IExZbidOpeningArrangeService;
import org.jeecg.modules.exZbidOpeningArrange.vo.ExZbidOpeningArrangePage;
import org.jeecg.modules.exZbidOpeningArrange.vo.ExZbidOpeningArrangeParam;
import org.jeecg.modules.gcProject.vo.StatusEnum;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 场地预约
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "场地预约")
@RestController
@RequestMapping("/exZbidOpeningArrange/exZbidOpeningArrange")
@Slf4j
public class ExZbidOpeningArrangeController {
    @Autowired
    private IExZbidOpeningArrangeService exZbidOpeningArrangeService;
    @Autowired
    private IExZbidChangdiandbdService exZbidChangdiandbdService;

    @Autowired
    private IExBiddingRoomService exBiddingRoomService;
    @Autowired
    private IExSectionService exSectionService;
    /**
     * 分页列表查询
     *
     * @param exZbidOpeningArrange
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "场地预约-分页列表查询")
    @ApiOperation(value = "场地预约-分页列表查询", notes = "场地预约-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExZbidOpeningArrange>> queryPageList(ExZbidOpeningArrange exZbidOpeningArrange,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        QueryWrapper<ExZbidOpeningArrange> queryWrapper = QueryGenerator.initQueryWrapper(exZbidOpeningArrange, req.getParameterMap());
        Page<ExZbidOpeningArrange> page = new Page<ExZbidOpeningArrange>(pageNo, pageSize);
        IPage<ExZbidOpeningArrange> pageList = exZbidOpeningArrangeService.page(page, queryWrapper);
        List<String> roomIds = pageList.getRecords().stream().map(ExZbidOpeningArrange::getBiddingRoomId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(roomIds)){
            List<ExBiddingRoom> exBiddingRoomList = exBiddingRoomService.listByIds(roomIds);
            for (ExZbidOpeningArrange ex: pageList.getRecords()) {
                Optional<ExBiddingRoom> optional = exBiddingRoomList.stream().filter(o -> o.getId().equals(ex.getBiddingRoomId())).findFirst();
                if(optional.isPresent()){
                    ExBiddingRoom exBiddingRoom = exBiddingRoomList.stream().filter(o -> o.getId().equals(ex.getBiddingRoomId())).findFirst().get();
                    if(exBiddingRoom!=null){
                        ex.setBiddingRoomName(exBiddingRoom.getRoomName());
                    }
                }
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param exZbidOpeningArrangePage
     * @return
     */
    @AutoLog(value = "场地预约-添加")
    @ApiOperation(value = "场地预约-添加", notes = "场地预约-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExZbidOpeningArrangePage exZbidOpeningArrangePage) {
        ExZbidOpeningArrange exZbidOpeningArrange = new ExZbidOpeningArrange();
        BeanUtils.copyProperties(exZbidOpeningArrangePage, exZbidOpeningArrange);
        // TODO 增加验证，开标室是否被其他预约了
        if(StringUtils.isEmpty(exZbidOpeningArrangePage.getExSectionIds())){
            return Result.error("没有对应的标段");
        }
        List<String> exSectionIds = Arrays.asList(exZbidOpeningArrangePage.getExSectionIds().split(","));
        List<ExSection> exSectionList = exSectionService.selectByIds(exSectionIds.toArray(new String[0]));
        if(CollectionUtils.isEmpty(exSectionList)){
            return Result.error("没有对应的标段");
        }
        for (int i = 0; i < exSectionList.size(); i++) {
            ExSection exSection = exSectionList.get(i);
            ExZbidOpeningArrange bySectionId = exZbidOpeningArrangeService.getBySectionId(exSection.getId());
            if (ObjectUtil.isNotEmpty(bySectionId)) {
                return Result.error("选择的标段 [ " + exSection.getBidSectionName() + " ] 已经存在预约信息");
            }
        }
        String sectionNames = exSectionList.stream().map(ExSection::getBidSectionName).collect(Collectors.joining());
        String sectionCodes = exSectionList.stream().map(ExSection::getBidSectionCode).collect(Collectors.joining());
        exZbidOpeningArrange.setBidSectionName(sectionNames);
        exZbidOpeningArrange.setBidSectionCode(sectionCodes);
        exZbidOpeningArrangeService.saveMain(exZbidOpeningArrange, exZbidOpeningArrangePage.getExZbidChangdiandbdList(), exZbidOpeningArrangePage.getRoomRecordList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exZbidOpeningArrangePage
     * @return
     */
    @AutoLog(value = "场地预约-编辑")
    @ApiOperation(value = "场地预约-编辑", notes = "场地预约-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExZbidOpeningArrangePage exZbidOpeningArrangePage) {
        ExZbidOpeningArrange exZbidOpeningArrange = new ExZbidOpeningArrange();
        BeanUtils.copyProperties(exZbidOpeningArrangePage, exZbidOpeningArrange);
        ExZbidOpeningArrange exZbidOpeningArrangeEntity = exZbidOpeningArrangeService.getById(exZbidOpeningArrange.getId());
        if (exZbidOpeningArrangeEntity == null) {
            return Result.error("未找到对应数据");
        }
        exZbidOpeningArrangeService.updateMain(exZbidOpeningArrange, exZbidOpeningArrangePage.getExZbidChangdiandbdList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "场地预约-通过id删除")
    @ApiOperation(value = "场地预约-通过id删除", notes = "场地预约-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        exZbidOpeningArrangeService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "场地预约-批量删除")
    @ApiOperation(value = "场地预约-批量删除", notes = "场地预约-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.exZbidOpeningArrangeService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "场地预约-通过id查询")
    @ApiOperation(value = "场地预约-通过id查询", notes = "场地预约-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExZbidOpeningArrange> queryById(@RequestParam(name = "id", required = true) String id) {
        ExZbidOpeningArrange exZbidOpeningArrange = exZbidOpeningArrangeService.getById(id);
        if (exZbidOpeningArrange == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(exZbidOpeningArrange);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "场地预约标段关联表通过主表ID查询")
    @ApiOperation(value = "场地预约标段关联表主表ID查询", notes = "场地预约标段关联表-通主表ID查询")
    @GetMapping(value = "/queryExZbidChangdiandbdByMainId")
    public Result<List<ExZbidChangdiandbd>> queryExZbidChangdiandbdListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ExZbidChangdiandbd> exZbidChangdiandbdList = exZbidChangdiandbdService.selectByMainId(id);
        return Result.OK(exZbidChangdiandbdList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param exZbidOpeningArrange
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExZbidOpeningArrange exZbidOpeningArrange) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ExZbidOpeningArrange> queryWrapper = QueryGenerator.initQueryWrapper(exZbidOpeningArrange, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ExZbidOpeningArrange> exZbidOpeningArrangeList = exZbidOpeningArrangeService.list(queryWrapper);

        // Step.3 组装pageList
        List<ExZbidOpeningArrangePage> pageList = new ArrayList<ExZbidOpeningArrangePage>();
        for (ExZbidOpeningArrange main : exZbidOpeningArrangeList) {
            ExZbidOpeningArrangePage vo = new ExZbidOpeningArrangePage();
            BeanUtils.copyProperties(main, vo);
            List<ExZbidChangdiandbd> exZbidChangdiandbdList = exZbidChangdiandbdService.selectByMainId(main.getId());
            vo.setExZbidChangdiandbdList(exZbidChangdiandbdList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "场地预约列表");
        mv.addObject(NormalExcelConstants.CLASS, ExZbidOpeningArrangePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("场地预约数据", "导出人:" + sysUser.getRealname(), "场地预约"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ExZbidOpeningArrangePage> list = ExcelImportUtil.importExcel(file.getInputStream(), ExZbidOpeningArrangePage.class, params);
                for (ExZbidOpeningArrangePage page : list) {
                    ExZbidOpeningArrange po = new ExZbidOpeningArrange();
                    BeanUtils.copyProperties(page, po);
                    exZbidOpeningArrangeService.saveMain(po, page.getExZbidChangdiandbdList(), page.getRoomRecordList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @ApiOperation(value = "场地预约-记录", notes = "场地预约-记录")
    @GetMapping(value = "/recordList")
    public Result<List<ExZbidOpeningArrange>> recordList(ExZbidOpeningArrange exZbidOpeningArrange,
                                                             HttpServletRequest req) {
        QueryWrapper<ExZbidOpeningArrange> queryWrapper = QueryGenerator.initQueryWrapper(exZbidOpeningArrange, req.getParameterMap());
        List<ExZbidOpeningArrange> list = exZbidOpeningArrangeService.list(queryWrapper);
        return Result.OK(list);
    }

    @AutoLog(value = "提交送审")
    @ApiOperation(value = "提交送审", notes = "提交送审")
    @PostMapping(value = "/submitAudit")
    public Result<String> submitAudit(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExZbidOpeningArrange byId = exZbidOpeningArrangeService.getById(id);
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        byId.setStatus(StatusEnum.SUBMIT.getCode());
        byId.setUpdateTime(new Date());
        byId.setUpdateBy(sysUser.getUsername());
        exZbidOpeningArrangeService.updateById(byId);
        return Result.OK("提交送审成功!");
    }

    @AutoLog(value = "项目进场-审核")
    @ApiOperation(value = "项目进场-审核", notes = "项目进场-审核")
    @PostMapping(value = "/audit")
    public Result<String> audit(@RequestBody ExZbidOpeningArrangeParam param) {
        exZbidOpeningArrangeService.audit(param);
        return Result.OK("审核成功!");
    }
}
